package org.xue.snowmall.authserver.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.xue.snowmall.authserver.feign.ThirdPartyService;
import org.xue.snowmall.authserver.service.UserRecordService;
import org.xue.snowmall.authserver.vo.UserLoginVo;
import org.xue.snowmall.authserver.vo.UserRegisterVo;
import org.xue.snowmall.common.utils.R;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 小刘的小张
 * @version 1.0
 * @description: TODO
 * @date 2021/9/19 9:11
 */
@Controller
public class WebLoginController {

    @Autowired
    public UserRecordService userRecordService;

    @Autowired
    private ThirdPartyService thirdPartyService;
    @RequestMapping({"/","login.html"})
    public String index(@RequestParam(value = "url" , defaultValue = "snow-mall.com" ,required = false) String url
    , Model model) {

        model.addAttribute("url",url);
        return "login";
    }
    @RequestMapping("/register.html")
    public String toRegister() {

        return "register";
    }
    @PostMapping("/register")
    public String register(UserRegisterVo user) {
        return userRecordService.register(user);
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo) {
        return userRecordService.login(vo);
    }

    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        //生成随机数
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        String codeNum = String.valueOf(code);
        //feign调用发送短信
        return thirdPartyService.sendCode(phone,codeNum);
    }

    @GetMapping(value = "/loguot.html")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        request.getSession().invalidate();
        return "redirect:http://snow-mall.com";
    }
}
